
import qs from 'qs'
export default class MpConnectNative {
  constructor () {
    this.instance = null
    this.reset = true
    this.bridge = wx
    this.defaultPage = '/pages/default/main'
  }

  static getInstance () {
    console.log('MpConnectNative getInstance Name:', this.name)
    if (!this.instance) {
      this.instance = new MpConnectNative()
    }
    return this.instance
  }

  formatRoute (uri) {
    return uri
  }

  /**
   * 调起原生webview通用
   * @param {*} data
   */
  goHome () {
    this.bridge.switchTab({
      url: '/pages/index/main'
    })
  }

  /**
   * 调起原生webview通用
   * @param {*} data
   */
  showMessage (data, replace = true) {
    if (!data) {
      return
    }
    mpvue.setStorageSync('message', data)
    const params = {
      url: this.formatRoute(this.defaultPage)
    }
    if (replace) {
      this.bridge.redirectTo(params)
    } else {
      this.bridge.navigateTo(params)
    }
  }

  /**
   * 调起原生webview通用
   * @param {*} data
   */
  callNativeHandler (data) {
    if (!data) {
      return
    }
    console.group('DefaultPageUnload')
    wx.removeStorageSync('PAGE_PARAMS')
    console.groupEnd('DefaultPageUnload')
    if (typeof (data) === 'string') {
      this.bridge.navigateTo({
        url: data
      })
    } else if (typeof (data) === 'object') {
      const {type, route, params, allow, tips} = data
      if (allow) {
        const mine = mpvue.getStorageSync('mine')
        console.log('mine', mine)
        console.log('mine allew', mine[allow])
        if (!mine[allow]) {
          wx.showToast({
            title: tips,
            icon: 'none',
            duration: 2000
          })
          return
        }
      }
      if (type === 'back') {
        this.bridge.navigateBack({
          delta: route
        })
        return
      }
      var url = route
      if (params && typeof (params) === 'object') {
        console.log('native link params:', params)
        url += '?' + qs.stringify(params)
        wx.setStorageSync('PAGE_PARAMS', params)
      }
      console.log('native link url:', url)
      if (type === 'push') {
        console.log('push=>>>>', url)
        this.bridge.navigateTo({
          url: url
        })
      } else if (type === 'replace') {
        this.bridge.redirectTo({
          url: url
        })
      } else if (type === 'tabbar') {
        this.bridge.switchTab({
          url: url
        })
      } else {
        wx.reLaunch({
          url: url
        })
      }
    }
  }
}
